package com.my.blog.website.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 七牛云配置文件
 *
 * @author: gyh
 * @date: 2019/12/12
 */
@Component
public class QiniuUploadConfig {
    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")

    @Getter
    private String bucket;

    /**
     * 域名
     */
    @Value("${qiniu.prefix}")
    @Getter
    private String domain;

    private long expireSeconds = 60 * 60 * 2;

    /**
     * policy
     *
     * @return
     */
    private StringMap getPolicy() {
        JSONObject body = new JSONObject();
        body.put("uuid", "$(uuid)");
        body.put("name", "$(key)");
        body.put("hash", "$(etag)");
        body.put("size", "$(fsize)");
        body.put("type", "$(mimeType)");
        body.put("url", this.domain + "/$(key)");

        String returnBody = JSONUtil.toJsonStr(body);

        StringMap policy = new StringMap();
        policy.put("returnBody", returnBody);

        return policy;
    }

    /**
     * Auth
     *
     * @return
     */
    private Auth auth() {
        return Auth.create(this.accessKey, this.secretKey);
    }

    /**
     * uploadToken
     */
    public String upToken() {
        return this.auth().uploadToken(this.bucket, null, this.expireSeconds, this.getPolicy());
    }

    /**
     * 华南机房
     */
//    private final Region REGION = Region.huadong();
    private final Region REGION = Region.huanan();

    /**
     * 构造一个带指定Region对象的配置类
     *
     * @return
     */
    private Configuration configuration() {
        return new Configuration(this.REGION);
    }

    /**
     * 上传 Manager
     */
    public UploadManager uploadManager() {
        return new UploadManager(this.configuration());
    }

    /**
     * 管理 Manger，用户移动、复制和删除等
     */
    public BucketManager bucketManager() {
        return new BucketManager(this.auth(), this.configuration());
    }
}
